package com.example.demo.interceptor;

import com.alibaba.druid.util.StringUtils;
import com.example.demo.utils.TokenUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    public TokenUtil tokenUtil;
    public LoginInterceptor(TokenUtil tokenUtil){this.tokenUtil=tokenUtil;}
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = tokenUtil.getToken(request);
        //token检查
        if (StringUtils.isEmpty(token)) {
            //返回给前端提示
            PrintWriter writer = response.getWriter();
            writer.println("Access blocked");
            writer.flush();
            writer.close();
            //response.sendRedirect("");
            System.out.println("访问已拦截");
            return false;
        }
        return true;
    }
}
